<template>
  <div class="wrapper-add-edit">
    <el-form ref="refForm" :model="formData" :rules="rules" :inline-message="true" label-width="120px">
      <el-form-item label="选择上级路由">
        <el-tree-select
          v-model="formData.idParent"
          :data="treeSelectData"
          :props="{ value: 'id', label: 'title' }"
          :render-after-expand="false"
          :current-node-key="0"
          value-key="id"
          placeholder="选择上级路由"
          check-strictly
        />
      </el-form-item>

      <el-form-item label="菜单显示名称" prop="title">
        <el-col :span="10">
          <el-input v-model="formData.title" placeholder="显示在菜单上的名称" />
        </el-col>
        <el-col :span="13" :push="1">
          <p class="info">设置菜单名称。<span>例：“读者管理”</span></p>
        </el-col>
      </el-form-item>

      <el-form-item label="url" prop="clientUrl">
        <el-col :span="10">
          <el-input v-model="formData.clientUrl" placeholder="设置路由（菜单）的URL" />
        </el-col>
        <el-col :span="13" :push="1">
          <p class="info">
            该路由对应的客户端的url，由其父路由的url组合而成。 因此除了1级路由需要“/”开头，其他只需填写该路由的相对url。
            根目录是0级路由，1级路由以“/”开头，2级及以上则无需“/”开头。
            <br />
            <span>例：1级“/system”，2级“admin”，3级“add”</span>
          </p>
        </el-col>
      </el-form-item>

      <el-form-item label="路由英文标识">
        <el-col :span="10">
          <el-input v-model="formData.routeName" placeholder="路由英文标识" />
        </el-col>
        <el-col :span="13" :push="1">
          <p class="info">
            对应路由 name，如果此路由有子路由，则留空。
            <br />
            <span>例：1级“系统管理”填""，2级“管理员管理”填“”，3级“添加管理员”填“AddAdmin”</span>
          </p>
        </el-col>
      </el-form-item>

      <el-form-item label="组件路径">
        <el-col :span="10">
          <el-input v-model="formData.componentPath" placeholder="路由对应的组件路径" />
        </el-col>
        <el-col :span="13" :push="1">
          <p class="info">
            该菜单对应的组件的路径，应当填写完整路径。
            <br />
            1级路由填“layout”，2级路由如果还有子路由，填“/system/index”，
            注意这是多级路由的解决办法，在"/views/system/index.vue"文件里还有一个 router-view。
            3级路由填写“/views”目录下对应组件完整路径，以“/”开头。
            <br />
            <span>例：1级路由填“layout”，2级填"/system/index"，3级填“/system/admin/add”</span>
          </p>
        </el-col>
      </el-form-item>

      <el-form-item label="转向路由地址">
        <el-col :span="10">
          <el-input v-model="formData.redirect" placeholder="设置路由的转向地址url" />
        </el-col>
        <el-col :span="13" :push="1">
          <p class="info">
            如果有子菜单，则需要填写此跳转url，没有子路由就留空。必须以“/”开头。
            <br />
            <span>例：1级填“/system/admin”，2级填“/system/admin/list_all”，3级留空“”</span>
          </p>
        </el-col>
      </el-form-item>

      <el-form-item label="图标">
        <el-col :span="10">
          <el-input v-model="formData.icon" placeholder="设置菜单Icon" />
        </el-col>
        <el-col :span="13" :push="1">
          <p class="info">
            设置显示在菜单上的Icon图标，只填写Icon的名字，不包括前后缀。
            <br />
            <span>例：“RemoveFilled”、“CircleCheck”</span>
          </p>
        </el-col>
      </el-form-item>

      <el-form-item label="是否还有子路由">
        <el-col :span="10">
          <el-radio-group v-model="formData.flagShowLeft">
            <el-radio-button value="true">是</el-radio-button>
            <el-radio-button value="false">否</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="13" :push="1">
          <p class="info">有子路由，设置成“是”；没有子路由，设置成“否”</p>
        </el-col>
      </el-form-item>

      <el-form-item label="是否在菜单显示">
        <el-col :span="10">
          <el-radio-group v-model="formData.flagHidden">
            <el-radio-button value="false">是</el-radio-button>
            <el-radio-button value="true">否</el-radio-button>
          </el-radio-group>
        </el-col>
        <el-col :span="13" :push="1">
          <p class="info">
            是否在左侧边栏的菜单显示。
            <br />
            <span>例：“添加管理员”要在菜单显示，如果是“编辑管理员”就不需要在菜单显示了。</span>
          </p>
        </el-col>
      </el-form-item>

      <el-form-item label="排序值">
        <el-col :span="10">
          <el-input v-model="formData.weight" onkeyup="value=value.replace(/[^\d]/g,'')" style="width: 50px" />
        </el-col>
        <el-col :span="13" :push="1">
          <p class="info">排序值，值越小越在上</p>
        </el-col>
      </el-form-item>

      <el-form-item>
        <el-button type="success" @click="onAdd()">确定添加</el-button>
        <el-button type="primary" @click="onReset">重置</el-button>
        <el-button type="info" @click="onBack2List">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { toastError, toastSuccess } from '@/utils/toast'
import { AryToTree } from '@/utils/array'

import router from '@/router'
import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'RouteAddView',
  components: {},
  setup() {
    const allRouteList = ref([])
    const treeSelectData = ref([])
    const formData = ref({
      id: 0,
      idParent: 1,
      level: 0,
      clientUrl: '',
      routeName: '',
      componentPath: '',
      redirect: '',
      title: '',
      icon: '',
      flagShowLeft: false,
      flagHidden: false,
      weight: 99,
    })
    const refForm = ref(null)

    const rules = ref({
      title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
      clientUrl: [{ required: true, message: '请输入客户端url', trigger: 'blur' }],
    })

    // 从服务器API得到所有的路由数组
    const listAllRoute = () => {
      store
        .dispatch('sys_front_route/listAll')
        .then((response) => {
          allRouteList.value = response
          treeSelectData.value = AryToTree(response, 0)
          console.log('treeSelectData.value：', treeSelectData.value)
        })
        .catch((error) => {
          console.log('从服务器API得到所有的路由数组出现错误：', error)
        })
    }
    // 提交表单
    const onAdd = () => {
      for (let i = 0; i < allRouteList.value.length; i++) {
        if (formData.value.idParent === allRouteList.value[i].id) {
          formData.value.level = allRouteList.value[i].level + 1
          break
        }
      }
      console.log('formData', formData.value)
      refForm.value.validate((valid) => {
        if (!valid) {
          toastError('表单验证失败！请检查您的输入！')
          return
        }
        // 表单验证通过
        store
          .dispatch('sys_front_route/add', formData.value)
          .then(() => {
            toastSuccess('添加成功！')
            router.push({ path: 'list-all' })
          })
          .catch((error) => {
            console.log('添加路由出现错误：', error)
            toastSuccess('添加路由出现错误：')
          })
      })
    }
    // 重置表单
    const onReset = () => {
      if (!refForm.value) return
      refForm.value.resetFields()
    }
    // 取消并返回列表页
    const onBack2List = () => {
      router.push({ path: 'list-all' })
    }

    onMounted(() => {
      listAllRoute()
    })

    return {
      rules,
      allRouteList,
      formData,
      treeSelectData,
      refForm,
      listAllRoute,
      onAdd,
      onReset,
      onBack2List,
    }
  },
})
</script>

<style lang="scss" scoped>
:deep(.el-form-item__content) {
  align-items: flex-start;
}
.info {
  span {
    color: #707070;
  }
}
</style>
